<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class ExamsUsersController extends AdminbaseController{
	
	protected $exams_model;
	protected $terms_model;
	protected $targets=array("_blank"=>"新标签页打开","_self"=>"本窗口打开");
	protected $question_types=array("1"=>"单选题","2"=>"多项选择题","3"=>"填空题","4"=>"判断题","5"=>"主观题");
	
	public function _initialize() {
		parent::_initialize();
		$this->exams_model = D("Admin/Exams");
		$this->terms_model = D("Portal/QuesTerms");
		$this->assign("question_types",$this->$question_types);
	}
	
	// 后台考试列表
	public function index($id=0,$term_id=0,$keyword=''){
	    
    	$map=null;
    	if($id>0) $map['a.id']=$id;
    	if($term_id>0) $map['a.exam_term']=$term_id;
    	//if($type_id>0) $map['a.exam_type']=$type_id;
    	if(!empty($keyword)) $map['a.exam_name']=$keyword;
    	if(isset($map))$map['_logic']='OR';
    	$this->_lists($map);
    	
    	$this->_getTree();
    	$this->display();
	}
	// 考试添加
	public function add(){
	    $paper_list=M('paper')->where('paper_type=1')->select();
	    $this->assign("paper_list",$paper_list);
    	$this->_getTree();
		$this->display();
	}
	
	
	// 考试添加提交
	public function add_exams(){
		if(IS_POST){
			if ($this->exams_model->create()!==false) {
				if ($this->exams_model->add()!==false) {
					$this->success("添加成功！", U("exams/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->exams_model->getError());
			}		
		}
	}
	
	// 考试编辑
	public function edit(){
		$id=I("get.id",0,'intval');
		$exams=$this->exams_model->where(array('id'=>$id))->find();
		$this->assign($exams);
		$this->assign("targets",$this->targets);
		$this->display();
	}
	
	// 考试编辑
	public function edit_exams(){
		if (IS_POST) {
			if ($this->exams_model->create()!==false) {
				if ($this->exams_model->save()!==false) {
					$this->success("保存成功！");
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->exams_model->getError());
			}
		}
	}
	
	// 考试排序
	public function listorders() {
		$status = parent::_listorders($this->exams_model);
		if ($status) {
			$this->success("排序更新成功！");
		} else {
			$this->error("排序更新失败！");
		}
	}
	
  // 考试排序
    public function sorts() {
        $status = parent::_sorts($this->term_relationships_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
    
    /**
     * 考试列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $term_id=I('request.term_id',0,'intval');
        //$type_id=I('request.type_id',0,'intval');
        
        if(!empty($term_id)){
            $where['exam_term']=$term_id;
            $term=$this->exams_model->where(array('exam_term'=>$term_id))->find();
            $this->assign("term",$term);
        }
        /* if(!empty($type_id)){
            $where['exam_type']=$term_id;
            $this->assign("type_id",$type_id);
        } */
    
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['exam_date']=array(
                array('EGT',$start_time)
            );
        }
    
        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['exam_date'])){
                $where['exam_date']=array();
            }
            array_push($where['exam_date'], array('ELT',$end_time));
        }
    
        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['exam_name']=array('like',"%$keyword%");
        }
        	
        $this->exams_model
        ->alias("a")
        ->where($where);
    
        if(!empty($term_id)){
            $this->exams_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
    
        $count=$this->exams_model->count();
        	
        $page = $this->page($count, 20);
        	
        $this->exams_model
        ->alias("a")
        ->join("__USERS__ c ON a.user_id = c.id")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.exam_date DESC");
        if(empty($term_id)){
            $this->exams_model->field('a.*,c.user_login,c.user_nicename');
        }else{
            $this->exams_model->field('a.*,c.user_login,c.user_nicename,b.listorder,b.tid');
            $this->exams_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
        $exams=$this->exams_model->select();
        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("exams",$exams);
    }
       
    // 获取考试分类树结构 select 形式
    private function _getTree(){
        $term_id=empty($_REQUEST['term_id'])?6:intval($_REQUEST['term_id']);
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 获取考试分类树结构
    private function _getTermTree($term=array()){
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 考试删除
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->exams_model->where(array('id'=>$id))->save(array('exam_status'=>3)) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            	
            if ($this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>3))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
    
    // 考试审核
    public function check(){
        if(isset($_POST['ids']) && $_GET["check"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>1)) !== false ) {
                $this->success("审核成功！");
            } else {
                $this->error("审核失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["uncheck"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>0)) !== false) {
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }
    }
    
    // 考试置顶
    public function top(){
        if(isset($_POST['ids']) && $_GET["top"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>1))!==false) {
                $this->success("置顶成功！");
            } else {
                $this->error("置顶失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["untop"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>0))!==false) {
                $this->success("取消置顶成功！");
            } else {
                $this->error("取消置顶失败！");
            }
        }
    }
    
    // 考试推荐
    public function recommend(){
        if(isset($_POST['ids']) && $_GET["recommend"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["unrecommend"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }
    
    // 考试批量移动
    public function move(){
        if(IS_POST){
            if(isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])){
                $old_term_id=I('get.old_term_id',0,'intval');
                $term_id=I('post.term_id',0,'intval');
                if($old_term_id!=$term_id){
                    $ids=explode(',', I('get.ids/s'));
                    $ids=array_map('intval', $ids);
    
                    foreach ($ids as $id){
                        $this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$old_term_id))->delete();
                        $find_relation_count=$this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$term_id))->count();
                        if($find_relation_count==0){
                            $this->term_relationships_model->add(array('object_id'=>$id,'term_id'=>$term_id));
                        }
                    }
                     
                }
                 
                $this->success("移动成功！");
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->exams_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
   
    
    // 考试回收站列表
    public function recyclebin(){
        $this->_lists(array('exam_status'=>array('eq',3)));
        $this->_getTree();
        $this->display();
    }
    
    // 清除已经删除的考试
    public function clean(){
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status=$this->exams_model->where(array("id"=>array('in',$ids),'exam_status'=>3))->delete();
            $this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
            	
            if ($status!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }else{
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                $status=$this->exams_model->where(array("id"=>$id,'exam_status'=>3))->delete();
                $this->term_relationships_model->where(array('object_id'=>$id))->delete();
    
                if ($status!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }
    
    // 考试还原
    public function restore(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->exams_model->where(array("id"=>$id,'exam_status'=>3))->save(array("exam_status"=>"1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }
	
}